package com.jkoss.wine.system.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.SqlHelper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.jkoss.common.util.CommonUtil;
import com.jkoss.wine.system.entity.MerchantEmployees;
import com.jkoss.wine.system.entity.MerchantEmployeesRole;
import com.jkoss.wine.system.mapper.MerchantEmployeesMapper;
import com.jkoss.wine.system.mapper.MerchantEmployeesRoleMapper;
import com.jkoss.wine.system.service.IMerchantEmployeesService;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author chair
 * @since 2018-09-20
 */
@Service
public class MerchantEmployeesServiceImpl extends ServiceImpl<MerchantEmployeesMapper, MerchantEmployees> implements IMerchantEmployeesService {

	@Autowired
	private MerchantEmployeesRoleMapper merchantEmployeesRoleMapper;

	@Override
	public boolean insertMerchantEmployees(MerchantEmployees entity, String[] pid) {
		if (super.insert(entity)) {
			return authorization(entity, pid);
		}
		return false;
	}

	@Override
	public boolean updateMerchantEmployees(MerchantEmployees entity, String[] pid) {
		if (authorization(entity, pid)) {
			return super.updateById(entity);
		}
		return false;
	}

	private boolean authorization(MerchantEmployees entity, String[] pid) {
		// 删除所有角色权限
		Wrapper wrapper = Condition.create().eq("meid", entity.getEmployeeId());
		merchantEmployeesRoleMapper.delete(wrapper);

		if (!CommonUtil.isBlank(pid)) {
			List<MerchantEmployeesRole> rolePermissions = new ArrayList();
			for (String ridStr : pid) {
				MerchantEmployeesRole tpEmployRole = new MerchantEmployeesRole();
				tpEmployRole.setMeid(entity.getEmployeeId());
				tpEmployRole.setRid(ridStr);
				rolePermissions.add(tpEmployRole);
			}
			if (retBool(merchantEmployeesRoleMapper.insertBatch(rolePermissions))) {
				return true;
			}
		}
		return false;
	}

	@Override
	public List selectEmployeesByRole(String rname) {
		Wrapper wrapper = Condition.create().ne("me.del", 1).eq("r.name", rname).eq("me.employee_state", 0);
		return baseMapper.selectEmployeesByRole(wrapper);
	}

	@Override
	public Page selectVoByPage(Page page, Wrapper wrapper) {
		SqlHelper.fillWrapper(page, wrapper);
		page.setRecords(baseMapper.selectVoByPage(page, wrapper));
		return page;
	}
}
